import { createStore } from 'vuex'
import { nanoid } from 'common/utils/nanoid'
import Cart from './modules/cart'

const state = function() {
  return {
    userName: 'admin',
    token: 'xxxxxxxx',
    favorites: []
  }
}

const getters = {
  latestFavorite(state, getters) {
    if (state.favorites) {
      return state.favorites[getters.favoriteCount -1]
    } else {
      return ''
    }
  },
  favoriteCount(state) {
    return state.favorites.length
  }
}

const mutations = {
  addFavorite(state, favorite){
    if (state.favorites.indexOf(favorite) < 0){
      state.favorites.push(favorite)
    }
  },
  clearAccount(state){
    state.userName = ''
    state.token = ''
  },
  updateAccount(state, account){
    state.userName = account.userName
    state.token    = account.token
  }
}

const actions = {
  login({ commit }, identityInfo){
    return new Promise((resolve, reject)=>{
      //simulate login to server
      if (identityInfo.username && identityInfo.password) {
        let token = nanoid()
        commit('updateAccount', {userName: identityInfo.username, token})
        resolve('login successfully.')
      }else{
        reject('login failed.')
      }
    })
  },
  logout(context){
    setTimeout(()=>{
      context.commit('clearAccount')
    }, 1000)
  }
}

export default createStore({
  state,
  getters,
  mutations,
  actions,
  modules: {
    Cart
  }
})